﻿using IJhbyService;
using JhbyCommon.CommonModel;
using JhbyCommon.JhbyCommon.CommonMethods;
using JhbyHelper;
using JhbyModel.Models;
using JhbyWebApi.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JhbyWebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SystemLogsController : ControllerBase
    {
        jhbyrbacContext _context = null;
        //注入
        ISystemLogService _systemLogService;
        public SystemLogsController(ISystemLogService systemLogService)
        {
            _systemLogService = systemLogService;
        }
        /// <summary>
        /// 日志列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="StartTime"></param>
        /// <param name="EndTime"></param>
        /// <param name="LogType"></param>
        /// <param name="OperateType"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetList")]
        public string GetList(int pageIndex, int pageSize, string StartTime, string EndTime, int LogType, int OperateType)
        {
            Response response1 = new Response();
            //token验证 
            int verifytokenid = TokenHelper.VerifyToken(HttpContext.Request);
            response1.Code = verifytokenid;
            if (verifytokenid == 0)
            {
                response1.data =  _systemLogService.GetList(pageIndex, pageSize, StartTime, EndTime, LogType, OperateType);
            }
            else if (verifytokenid == 1)
            {
                response1.message = "访问用户不存在！";
            }
            else if (verifytokenid == 2)
            {
                response1.message = "Token验证失败！";
            }
            else
            {
                response1.message = "账号已经在其他地方登陆！";
            }
            return JsonConvert.SerializeObject(response1);
        }
        [HttpGet]
        [Route("ExcelExport")]
        /// <summary>
        /// excel导入导出
        /// </summary>
        /// <returns></returns> 
        public ActionResult ExcelExport(string StartTime, string EndTime, int LogType, int OperateType)
        {

            try
            {
                #region 获取基本数据
                var predic = PredicateBuilder.True<Systemlogs>();

                if (!string.IsNullOrEmpty(StartTime) && !string.IsNullOrEmpty(EndTime))
                {
                    predic = predic.And(x => x.CreateDate >= Convert.ToDateTime(StartTime) && x.CreateDate <= Convert.ToDateTime(EndTime).AddDays(1).AddSeconds(-1));
                }
                if (LogType > 0)
                {
                    predic = predic.And(x => x.LogType == OperateType);
                }
                if (OperateType > 0)
                {
                    predic = predic.And(x => x.OperateType == OperateType);
                }
                var query = _context.Systemlogs.Where(predic).ToList();
                #endregion 获取基本数据

                #region 将数据导出到临时文件夹

                string newFileName = DateTime.Now.ToString("yyyyMMMMdddd") + System.Guid.NewGuid().ToString("N") + ".xlsx"; //随机生成新的文件名
                string filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "日志信息") + newFileName; //临时文件    本地的路径
                UTF8Encoding utf8 = new UTF8Encoding();
                byte[] buffer = utf8.GetBytes(filePath);
                filePath = utf8.GetString(buffer);

                //文件是否存在
                FileInfo file = new FileInfo(filePath);

                using (ExcelPackage package = new ExcelPackage(file))
                {
                    //添加worksheet
                    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add($"sheet1");
                    //添加表头
                    var columnList = new List<string>();
                    columnList.Add("序号");
                    columnList.Add("日志类型");
                    columnList.Add("操作类型");
                    columnList.Add("操作人");
                    columnList.Add("操作内容");
                    columnList.Add("操作时间");

                    for (int i = 0; i < columnList.Count; i++)
                    {
                        worksheet.Cells[1, i + 1].Value = columnList[i];//列头
                        worksheet.Cells[1, i + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;//设置样式类型
                        worksheet.Cells[1, i + 1].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(255, 255, 255));//设置单元格背景色
                        worksheet.Cells[1, i + 1].Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Black);//设置单元格所有边框
                        worksheet.Cells[1, i + 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;//居中
                    }
                    int row = 2;
                    foreach (var item in query)
                    {
                        //添加数据

                        worksheet.Cells[row, 1].Value = item.Id;//序号
                        worksheet.Cells[row, 1].Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Black);//设置单元格所有边框
                        worksheet.Cells[row, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;//居中
                        worksheet.Cells[row, 2].Value = Enum.GetName(typeof(BaseEnum.LogType), item.LogType);// item.LogType == 1 ? "登录" : item.LogType == 2 ? "操作" : "错误";//日志类型
                        worksheet.Cells[row, 2].Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Black);//设置单元格所有边框
                        worksheet.Cells[row, 2].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;//居中
                        worksheet.Cells[row, 3].Value = Enum.GetName(typeof(BaseEnum.OperateType), item.OperateType); //item.OperateType == 1 ? "增加" : item.LogType == 2 ? "删除" : item.LogType == 3 ? "修改" : item.LogType == 4 ? "登录" : "错误";//操作类型
                        worksheet.Cells[row, 3].Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Black);//设置单元格所有边框
                        worksheet.Cells[row, 3].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;//居中
                        worksheet.Cells[row, 4].Value = item.Operator;//操作人
                        worksheet.Cells[row, 4].Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Black);//设置单元格所有边框
                        worksheet.Cells[row, 4].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;//居中
                        worksheet.Cells[row, 5].Value = item.Content;//操作内容
                        worksheet.Cells[row, 5].Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Black);//设置单元格所有边框
                        worksheet.Cells[row, 5].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;//居中
                        worksheet.Cells[row, 6].Value = item.CreateDate + "";//操作时间 
                        worksheet.Cells[row, 6].Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Black);//设置单元格所有边框
                        worksheet.Cells[row, 6].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;//居中

                        row++;
                    }

                    worksheet.Column(2).Width = 35;
                    worksheet.Column(3).Width = 25;
                    worksheet.Column(6).Width = 30;
                    worksheet.Column(7).Width = 30;
                    worksheet.Column(8).Width = 20;
                    worksheet.Column(9).Width = 20;
                    //保存workbook
                    package.Save();
                }
                using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    // 读取文件的 byte[]

                    byte[] bytes = new byte[fileStream.Length];

                    fileStream.Read(bytes, 0, bytes.Length);

                    fileStream.Close();

                    // 把 byte[] 转换成 Stream
                    Stream stream = new MemoryStream(bytes);

                    System.IO.File.Delete(filePath);
                    #endregion 将数据导出到临时文件夹 并且删除本地文件
                    return File(stream, "application/vnd.ms-excel", filePath);
                }
            }
            catch (Exception)
            {

                throw;
            }



        }
    }
}
